package org.popupcommunication.controller;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;





import javax.validation.Valid;

import org.popupcommunication.model.Message;
import org.popupcommunication.service.MessageManager;
import org.springframework.beans.factory.annotation.Autowired;
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("admin/configuration")
public class AdminConfigController {
	@Autowired MessageManager messageService;	
	Map<String, String> lstProp;

	// static private Log log = LogFactory.getLog(AdminConfigController.class);


	@RequestMapping(value = "/fichier/{fileConfig}", method = RequestMethod.GET)
	public String editConfiguration(HttpServletRequest request, Model model,
			@PathVariable String fileConfig) throws IOException {
		String fileToOpen = null;
		InputStream input = null;
		Properties prop = new Properties();
		switch (fileConfig) {
		case "general":
			fileToOpen = "config.properties";
			break;
		case "email":
			fileToOpen = "gmail.properties";
			break;
		}
		try {
			input = new FileInputStream(request.getSession()
					.getServletContext().getRealPath("/WEB-INF/" + fileToOpen));

			prop.load(input);
			lstProp = new HashMap<String, String>();
			Enumeration<?> e = prop.propertyNames();
			while (e.hasMoreElements()) {
				String key = (String) e.nextElement();
				String value = prop.getProperty(key);
				lstProp.put(key, value);
			}
			model.addAttribute("lstProp", lstProp);
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "admin/config";
	}

	@RequestMapping(value = "/fichier/{fileConfig}", method = RequestMethod.POST)
	public String modifyConfiguration(HttpServletRequest request,
			HttpServletResponse response, @PathVariable String fileConfig)
			throws IOException {
		String fileToOpen = null;
		String fileToRead = null;
		OutputStream output = null;
		Properties prop = new Properties();
		switch (fileConfig) {
		case "general":
			fileToOpen = "/WEB-INF/config.properties";
			fileToRead = "config.properties";
			break;
		case "email":
			fileToOpen = "/WEB-INF/gmail.properties";
			fileToRead = "gmail.properties";
			break;
		}
		// Reset: get default properties
		if (request.getParameter("reset") != null) {
			InputStream input = null;
			input = AdminConfigController.class.getClassLoader()
					.getResourceAsStream(fileToRead);
			// input = new FileInputStream(fileToRead);
			// load a properties file
			prop.load(input);
			try {
				output = new FileOutputStream(request.getSession()
						.getServletContext().getRealPath(fileToOpen));
				// save properties to project root folder
				prop.store(output, null);

			} catch (IOException io) {
				io.printStackTrace();
			} finally {
				if (output != null) {
					try {
						output.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}

		// Save: save properties
		else if (request.getParameter("enregistrer") != null) {
			Enumeration<?> en = request.getParameterNames();
			try {

				output = new FileOutputStream(request.getSession()
						.getServletContext().getRealPath(fileToOpen));
				while (en.hasMoreElements()) {
					String name = (String) en.nextElement();
					if (!name.equals("enregistrer"))
						prop.setProperty(name, request.getParameter(name)
								.toString());
				}
				// save properties to project root folder
				prop.store(output, null);

			} catch (IOException io) {
				io.printStackTrace();
			} finally {
				if (output != null) {
					try {
						output.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

			}
		}

		return "admin/index";
	}

	@RequestMapping(value = "/edit/messages", method = RequestMethod.GET)
	public String viewListMessages(Model model) {
		List<Message> lstMessages = messageService.getAllMessages();
		model.addAttribute("listMsg", lstMessages);
		return "admin/listMessages";			
	}
	@RequestMapping(value="/edit/messages/{idMessage}", method=RequestMethod.GET)
	public String editMessage (Model model, @PathVariable Integer idMessage){	
		Message msg = messageService.findById(idMessage);	
		model.addAttribute("msg", msg);	
		return "admin/editMessage";	
	}	
	@RequestMapping(value="/edit/messages/{idMessage}", method=RequestMethod.POST) 
    public String editingMessage(HttpServletRequest request,@ModelAttribute("msg") @Valid Message message, BindingResult result, @PathVariable Integer idMessage) {
		message.setIdMessage(idMessage);
		messageService.update(message);
		return "admin/index";	
	}
}
